<?php

class LoginController extends BaseController
{
    public static function getLoginInfo(){
        return [
            "isLogin" => $_SESSION['isLogin'],
            "user_id" => $_SESSION['user_id']
        ];
    }
    public function tryLogin($obj){
        if($_SESSION['isLogin']){
            return ReturnHelper::failed([],"当前会话已有账号登录，请先退出原有账号再尝试登录",403);
        }
        $phoneNumber=$obj['phoneNumber'];
        $password=$obj['password'];
        $verificationCode=$obj['verificationCode'];
        $userController=new UserController;
        $data=$userController->getList();
        $userData=$data['data'];
        if(VerificationController::checkVerification($verificationCode)){
            for ($i=0;$i<count($userData);$i++){
                if($phoneNumber==$userData[$i]['phone_num']&&$password==$userData[$i]['password']){
                    if($userData[$i]['is_login']==0){
                        $_SESSION['isLogin']=true;
                        $_SESSION['user_id']=$userData[$i]['user_id'];
                        $userController->update((int)$_SESSION['user_id'],['is_login'=>1,'user_id'=>$_SESSION['user_id']]);
                        return ReturnHelper::success([],"登录成功");
                    }
                    else
                        return ReturnHelper::failed([],"登录失败,该账户已被登录",401);
                }
            }
        }
        else
            return ReturnHelper::failed([],"验证码错误",402);
        return ReturnHelper::failed([],"登录失败，账号或密码错误");
    }
    public function logout(){
        $userController = new UserController();
        $userID=$_SESSION['user_id'];
        $obj['is_login']=0;
        $obj['user_id']=$userID;
        $userController->update((int)$userID,$obj);
        $_SESSION['isLogin']=false;
        $_SESSION['user_id']=null;

        return ReturnHelper::success([],"注销成功");
    }
}